package com.sc.adapter;

import java.util.List;

import com.sc.db.MarkRecord;
import com.sc.lane.R;
import com.sc.ui.ViewPointsActivity;
import com.sc.utils.StringUtil;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class RecordsAdapter extends BaseAdapter{
	private List<MarkRecord> mRecords;
	private LayoutInflater mInflater;
	private Context mContext;
	
	public RecordsAdapter(Context context, List<MarkRecord> records){
		this.mRecords = records;
		this.mContext = context;
		this.mInflater = LayoutInflater.from(mContext);
	}

	@Override
	public int getCount() {
		if(mRecords == null){
			return 0;
		}
		
		return mRecords.size();
	}

	@Override
	public Object getItem(int position) {
		if(mRecords == null){
			return null;
		}
		
		return mRecords.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		final int pos = position;
		holder = new ViewHolder();
		
		convertView = mInflater.inflate(R.layout.main_fragement_record_item, null);
		
		holder.staring = (TextView)convertView.findViewById(R.id.tv_starting);
		holder.destination = (TextView)convertView.findViewById(R.id.tv_destination);
		holder.description = (TextView)convertView.findViewById(R.id.tv_description);
		holder.status = (TextView)convertView.findViewById(R.id.tv_status);
		holder.details = (TextView)convertView.findViewById(R.id.tv_details);
		
		String starting = ((MarkRecord)mRecords.get(position)).getStarting();
		String destination = ((MarkRecord)mRecords.get(position)).getDestination();
		holder.staring.setText(StringUtil.getFriendlyLatLon(starting));
		holder.destination.setText(StringUtil.getFriendlyLatLon(destination));
		holder.description.setText(((MarkRecord)mRecords.get(position)).getDescription());
		int status = ((MarkRecord)mRecords.get(position)).getStatus();
		if(status == MarkRecord.MARK_DONE){
			holder.status.setText(convertView.getResources().getString(R.string.mark_done));
		}
		else{
			holder.status.setText(convertView.getResources().getString(R.string.mark_in_progess));
		}
		
		holder.details.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, ViewPointsActivity.class);
				intent.putExtra("record_id", ((MarkRecord)mRecords.get(pos)).getId());
				mContext.startActivity(intent);
			}
		});
		
		return convertView;
	}

	public final class ViewHolder {
		public TextView staring;
		public TextView destination;
		public TextView description;
		public TextView status;
		public TextView details;
	}
}
